Option Strict On
Option Explicit On

'Copyright (c) 2007-2010, William Severance, Jr., WESNet Designs
'All rights reserved.

'Redistribution and use in source and binary forms, with or without modification, are permitted
'provided that the following conditions are met:

'Redistributions of source code must retain the above copyright notice, this list of conditions
'and the following disclaimer.

'Redistributions in binary form must reproduce the above copyright notice, this list of conditions
'and the following disclaimer in the documentation and/or other materials provided with the distribution.

'Neither the name of William Severance, Jr. or WESNet Designs may be used to endorse or promote
'products derived from this software without specific prior written permission.

'Disclaimer: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
'            OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
'            AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE
'            FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
'            LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
'            INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
'            OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
'            IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

'Although I will try to answer questions regarding the installation and use of this software when
'such questions are submitted via e-mail to the below address, no promise of further
'support or enhancement is made nor should be assumed.

'Developer Contact Information:
'     William Severance, Jr.
'     WESNet Designs
'     679 Upper Ridge Road
'     Bridgton, ME 04009
'     Phone: 207-647-9375
'     E-Mail: bill@wesnetdesigns.com
'     Website: www.wesnetdesigns.com

Imports DotNetNuke
Imports DotNetNuke.Security
Imports DotNetNuke.Services.Exceptions

Imports System.Web.UI
Imports System.Collections.Generic

Namespace WESNet.DNN.Modules.EPrayer
    Partial Class PrintEPrayer
        Inherits EPrayerModuleBase

#Region "Private Members"
        Private _Filter As String = Nothing
        Private _RequestType As Integer = -1
        Private _Category As Integer = 0
        Private _DateRange As Integer = 1
        Private _Status As Integer = 0
        Private _Distribution As Integer = 1
        Private _OrderBy As String = "Order_Date_DESC"
        Private _SubjectLike As String = String.Empty
        Private _LastCategory As String = String.Empty
        Private _AuthorID As Integer = -1
        Private _DNNPrintMode As Boolean
#End Region

#Region "Public Properties"

        Public Property DNNPrintMode() As Boolean
            Get
                Return _DNNPrintMode
            End Get
            Set(ByVal value As Boolean)
                _DNNPrintMode = value
            End Set
        End Property

        Public Property RequestType() As Integer
            Get
                Return _RequestType
            End Get
            Set(ByVal value As Integer)
                _RequestType = value
            End Set
        End Property

        Public Property Category() As Integer
            Get
                Return _Category
            End Get
            Set(ByVal value As Integer)
                _Category = value
            End Set
        End Property

        Public Property DateRange() As Integer
            Get
                Return _DateRange
            End Get
            Set(ByVal value As Integer)
                _DateRange = value
            End Set
        End Property

        Public Property Status() As Integer
            Get
                Return _Status
            End Get
            Set(ByVal value As Integer)
                _Status = value
            End Set
        End Property

        Public Property Distribution() As Integer
            Get
                Return _Distribution
            End Get
            Set(ByVal value As Integer)
                _Distribution = value
            End Set
        End Property

        Public Property OrderBy() As String
            Get
                Return _OrderBy
            End Get
            Set(ByVal value As String)
                _OrderBy = value
            End Set
        End Property

        Public Property SubjectLike() As String
            Get
                Return _SubjectLike
            End Get
            Set(ByVal value As String)
                _SubjectLike = value
            End Set
        End Property

        Public Property AuthorID() As Integer
            Get
                Return _AuthorID
            End Get
            Set(ByVal value As Integer)
                _AuthorID = value
            End Set
        End Property

        Public ReadOnly Property Filter() As String
            Get
                Dim sb As New StringBuilder

                Select Case RequestType
                    Case -1
                        'all request types
                    Case 0
                        sb.Append("(IsPraise = 0)")
                    Case 1
                        sb.Append("(IsPraise <> 0)")
                End Select

                If Category > 0 Then
                    If sb.Length > 0 Then sb.Append(" AND ")
                    sb.AppendFormat("(R.CategoryID = {0})", Category)
                End If

                If DateRange < 1 Then
                    If sb.Length > 0 Then sb.Append(" AND ")
                    sb.AppendFormat("(LastPostDate >= convert(char(23), '{0:d}',126))", Now().AddDays(DateRange))
                End If

                If Status > 0 Then
                    If sb.Length > 0 Then sb.Append(" AND ")
                    sb.AppendFormat("(StatusID = {0})", Status)
                End If

                If RequestID > 0 Then
                    If sb.Length > 0 Then sb.Append(" AND ")
                    sb.AppendFormat("(R.RequestID = {0})", RequestID)
                End If

                If AuthorID > 0 Then
                    If sb.Length > 0 Then sb.Append(" AND ")
                    sb.AppendFormat("(P.CreatedByUserID = {0})", AuthorID)
                End If

                If SubjectLike <> String.Empty Then
                    Dim ps As New PortalSecurity
                    Dim s As String = ps.InputFilter(SubjectLike, PortalSecurity.FilterFlag.NoMarkup Or PortalSecurity.FilterFlag.NoScripting Or PortalSecurity.FilterFlag.NoSQL)
                    If sb.Length > 0 Then sb.Append(" AND ")
                    sb.AppendFormat("(R.Subject LIKE '%{0}%')", s)
                End If

                Return sb.ToString
            End Get
        End Property
#End Region

#Region "Event Handlers"

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Page_Load runs when the control is loaded
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Try

                If Not String.IsNullOrEmpty(Request.QueryString("postid")) Then
                    PostID = Convert.ToInt32(Request.QueryString("postid"))
                Else
                    PostID = Null.NullInteger
                End If

                If Not String.IsNullOrEmpty(Request.QueryString("authorid")) Then
                    AuthorID = Convert.ToInt32(Request.QueryString("authorid"))
                Else
                    AuthorID = Null.NullInteger
                End If

                If Not String.IsNullOrEmpty(Request.QueryString("dnnprintmode")) Then
                    DNNPrintMode = Boolean.Parse(Request.QueryString("dnnprintmode"))
                End If

                If Not String.IsNullOrEmpty(Request.QueryString("pagesize")) Then
                    PageSize = Convert.ToInt32(Request.QueryString("pagesize"))
                Else
                    PageSize = MyConfiguration.PageSize
                End If

                If Not String.IsNullOrEmpty(Request.QueryString("currentpage")) Then
                    CurrentPage = Convert.ToInt32(Request.QueryString("currentpage"))
                Else
                    CurrentPage = 1
                End If

                If Not IsPostBack Then
                    If PostID <> Null.NullInteger Then
                        Try
                            Dim epc As New EPrayerController
                            RequestID = epc.GetPost(PostID).RequestID
                        Catch
                            RequestID = Null.NullInteger
                        End Try
                    End If

                    If Not String.IsNullOrEmpty(Request.QueryString("type")) Then RequestType = Convert.ToInt32(Request.QueryString("type"))
                    If Not String.IsNullOrEmpty(Request.QueryString("category")) Then Category = Convert.ToInt32(Request.QueryString("category"))
                    If Not String.IsNullOrEmpty(Request.QueryString("daterange")) Then DateRange = Convert.ToInt32(Request.QueryString("daterange"))
                    If Not String.IsNullOrEmpty(Request.QueryString("status")) Then Status = Convert.ToInt32(Request.QueryString("status"))
                    If Not String.IsNullOrEmpty(Request.QueryString("distribution")) Then
                        Distribution = Convert.ToInt32(Request.QueryString("distribution")) And UserInfo.ViewableDistributions
                    Else
                        Distribution = UserInfo.ViewableDistributions
                    End If
                    If Not String.IsNullOrEmpty(Request.QueryString("orderby")) Then OrderBy = Request.QueryString("orderby")
                    If Not String.IsNullOrEmpty(Request.QueryString("subject")) Then
                        Dim s As String = Server.UrlDecode(Request.QueryString("subject"))
                        Dim ps As New PortalSecurity
                        SubjectLike = ps.InputFilter(s, PortalSecurity.FilterFlag.NoMarkup Or PortalSecurity.FilterFlag.NoScripting Or PortalSecurity.FilterFlag.NoSQL)
                    End If

                    GetRequests()

                End If
            Catch exc As Exception        'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        Protected Sub lstRequests_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles lstRequests.ItemDataBound
            If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then

                If OrderBy = "Order_Category" Then
                    Dim Category As String = CType(e.Item.DataItem, RequestInfo).Category
                    If Category <> _LastCategory Then
                        e.Item.FindControl("CategoryHeader").Visible = True
                        _LastCategory = Category
                    Else
                        e.Item.FindControl("CategoryHeader").Visible = False
                    End If
                End If

                Dim epc As New EPrayerController
                RequestID = Convert.ToInt32(lstRequests.DataKeys(e.Item.ItemIndex))
                Dim lstPosts As DataList = CType(e.Item.FindControl("lstPosts"), DataList)
                If Not lstPosts Is Nothing Then
                    Dim objPosts As List(Of PostInfo) = epc.GetPosts(RequestID, Distribution, True)
                    lstPosts.DataSource = objPosts
                    lstPosts.DataBind()
                End If
            End If
        End Sub
#End Region

#Region "Private Methods"

        Protected Sub GetRequests()
            Dim TotalRecords As Integer
            Dim epc As New EPrayerController
            Dim objRequests As List(Of RequestInfo)
            Dim IncludeExpired As Boolean = CanModerate
            objRequests = epc.GetRequests(ModuleId, Distribution, Filter, IncludeExpired, OrderBy, UserId, 0, CurrentPage - 1, TotalRecords)
            If objRequests.Count > 0 Then
                lstRequests.DataSource = objRequests
                lstRequests.DataBind()
            End If
        End Sub

        Protected Function GetNavigationParams() As String()
            Dim params As New ArrayList
            Dim result As String()
            If RequestID <> -1 Then params.Add("requestid=" & RequestID.ToString)
            If PostID <> -1 Then params.Add("postid=" & PostID.ToString)
            If AuthorID <> -1 Then params.Add("authorid=" & AuthorID.ToString)
            If PageSize <> MyConfiguration.PageSize Then params.Add("pagesize=" & PageSize.ToString)
            If CurrentPage <> 1 Then params.Add("currentpage=" & CurrentPage.ToString)
            If RequestType <> -1 Then params.Add("type=" & RequestType.ToString)
            If Category > 0 Then params.Add("category=" & Category.ToString)
            If DateRange < 1 Then params.Add("daterange=" & DateRange.ToString)
            If Status > 0 Then params.Add("status=" & Status.ToString)
            If Distribution <> UserInfo.ViewableDistributions Then params.Add("distribution=" & Distribution.ToString)
            If SubjectLike <> String.Empty Then
                Dim ps As New PortalSecurity
                Dim s As String = ps.InputFilter(SubjectLike, PortalSecurity.FilterFlag.NoMarkup Or PortalSecurity.FilterFlag.NoScripting Or PortalSecurity.FilterFlag.NoSQL)
                params.Add("subject=" & Server.UrlEncode(s))
            End If
            result = CType(params.ToArray(GetType(String)), String())
            Return result
        End Function

#End Region

        Protected Sub cmdReturn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdReturn.Click
            Try
                Response.Redirect(ReturnUrl, True)
            Catch exc As Exception
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub
    End Class
End Namespace
